package com.caichen.scheduler.task;

import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.caichen.scheduler.pojo.Order;
import com.caichen.scheduler.service.OrderService;
import com.caichen.utils.tools.DateUtils;

public class DistributionTask {

	
	private static Logger logger = LoggerFactory.getLogger(DistributionTask.class);
	
	@Autowired
	private OrderService orderService;
	
	
	public void run() {
		logger.info("========================================分销定时任务开始=================================================");
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, -31);
		String dateTime = DateFormatUtils.format(cal.getTime(), DateUtils.dateFormat_default);
		logger.info("==================================分销时间节点：" + dateTime + "========================================");
		logger.info("=======================================无退货订单分销开始================================================");
		List<Order> list = orderService.getNoRefundDistributionList(dateTime);
		if (list != null && list.size() > 0) {
			for (Order order : list) {
				if (order == null || StringUtils.isBlank(order.getMemberAccount())) continue;
				try {
					orderService.noRefundprocessDistribution(order);
				} catch (Exception e) {
					logger.error("Error 处理某个订单分销数据失败：", e);
				}
			}
		}
		logger.info("=======================================无退货订单分销结束================================================");
		
		logger.info("=======================================有退货订单分销开始================================================");
		List<Order> list_noRefund = orderService.getRefundDistributionList(dateTime);
		if (list_noRefund != null && list_noRefund.size() > 0) {
			for (Order order : list_noRefund) {
				if (order == null || StringUtils.isBlank(order.getMemberAccount())) continue;
				try {
					double refundAmount = orderService.getRefundOrderByOrderNo(order.getOrderNo());
					orderService.refundProcessDistribution(order, refundAmount);
				} catch (Exception e) {
					logger.error("Error 处理某个订单分销数据失败：", e);
				}
			}
		}
		logger.info("=======================================有退货订单分销结束================================================");
		logger.info("========================================分销定时任务结束=================================================");
	}
}
